<script setup lang='ts'>
import {
  removeJournalStore,
  setJournalStore
} from "@/utils/storage/journalTemp";
import * as journalApi from "@/api/journalApi";
import { ResponseCode, type IResponseBody } from '@/common/Responsetypes';
import {
  reactive,
  ref
} from 'vue';
import type { IJournalInfo } from "./types"
import moment from 'moment'
import JournalLocal from "@/components/journal-comps/journal-local.vue"
import { onLoad, onShow } from "@dcloudio/uni-app"
import _ from "lodash-es"
import type { IJournal, IPhotos } from "@/common/JournalTypes";
import { journalUpdated } from "@/bus";

const journalInfo: IJournalInfo = reactive({} as IJournalInfo)
const photos = ref<IPhotos[]>([])
const originRef = ref<"self" | "friend">("friend")

onLoad(async (e) => {
  journalInfo.id = e!.id as number

  if (!journalInfo.id) {
    uni.showToast({
      title: '日记信息错误',
      icon: 'none',
      duration: 1000,
      success: () => {
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }
    })
  } else {
    let journalResult: IResponseBody<IJournal> | null = null
    if (e!.origin === 'self') {
      originRef.value = "self"
      journalResult = await journalApi.findByid(journalInfo.id)
    } else if (e!.origin === 'friend') {
      journalResult = await journalApi.findOneOpenJournal(e!.mid, e!.uid, journalInfo.id,)
    }

    if (journalResult!.code === ResponseCode.PASS) {
      _.assign(journalInfo, journalResult!.data)
      photos.value = _.cloneDeep(journalInfo.photos)
      photos.value?.map((item) => {
        const url = item.url
        const image = new Image()
        image.src = url
        image.onload = () => {
          item.min = url
        }
      })

    }
  }

})

onShow(async () => {
  uni.$on(journalUpdated, (journal) => {
    if (journal.id === journalInfo.id) {
      _.assign(journalInfo, journal)
      photos.value = _.cloneDeep(journalInfo.photos)
      photos.value?.map((item) => {
        const url = item.url
        const image = new Image()
        image.src = url
        image.onload = () => {
          item.min = url
        }
      })
    }
  })
})

// 页面卸载时清除缓存
// onUnload(() => {
//   console.log('clear journal store');
//   removeJournalStore()
// })

function handleEdit() {
  setJournalStore(journalInfo)
  uni.navigateTo({
    url: `/pages/journal-modify/journal-modify`
  })
}

function handleDelete() {
  uni.showModal({
    title: '删除提示',
    content: '确定删除这篇日记吗？',
    success: (res) => {
      if (res.confirm) {
        journalApi.del(journalInfo.id).then((result) => {
          if (result.code === ResponseCode.PASS) {
            removeJournalStore()
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                uni.navigateBack()
              }
            })
          }
        })
      }
    }
  })
}

</script>

<template>
  <div class='journal-detail__container plr-40 pt-40'>
    <view class="journal-detail__content">
      {{ journalInfo.content }}
    </view>

    <JournalLocal :name="journalInfo?.marker_poi?.name" />

    <view class="journal-detail__album mt-40 mb-20">
      <uv-album :urls="photos" :keyName="'min'" multipleSize="160rpx" space="18rpx"></uv-album>
    </view>

    <!-- 可见范围 -->
    <uv-cell v-if="originRef === 'self'" class="mt-40" icon="account" title="谁可以看"
      :label="journalInfo.is_open ? '所有用户都可见' : '仅自己可见'">
      <template v-slot:value>
        <text class="mr-20">{{ journalInfo.is_open ? '公开' : '仅自己' }}</text>
      </template>
    </uv-cell>

    <view class="journal-detail__footer mt-40">
      <text class="created-time">最近更新：{{ moment(journalInfo.updatedAt).format('YYYY年MM月DD日 HH:mm') }}</text>
      <view class="operate ml-20" v-if="originRef === 'self'">
        <text style="color: rgb(167 167 167);">|</text>
        <!-- del -->
        <uv-icon name="trash" size="40rpx" @click="handleDelete"></uv-icon>
        <!-- modify -->
        <uv-icon name="edit-pen-fill" color="primary" size="40rpx" @click="handleEdit"></uv-icon>
      </view>
    </view>

  </div>
</template>

<style scoped lang='scss'>
@import "./journal-detail.scss";
</style>